package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
)

func working(start, end int)  {
	fmt.Println("正在爬取 %d 页数到 %d 页数", start, end)

	for i:=start; i<=end; i++ {
		url := "https://tieba.baidu.com/f?kw=%E6%9D%8E%E6%AF%85&ie=utf-8&pn="+strconv.Itoa((i-1)*50)
		result, err := HttpGet(url)
		if err != nil {
			fmt.Println("发送http请求出现错误", err)
			continue
		}

		//fmt.Println("当前页面地址：" + result)
		f, err := os.Create("C:/img/第" + strconv.Itoa(i) + "页内容.html")

		if err != nil {
			fmt.Println("创建文件失败 ", err)
			continue
		}
		f.WriteString(result)
		f.Close() //保存好一个文件，关闭一个文件
	}
}

func HttpGet(url string) (result string, err error) {

	resp, err1 := http.Get(url)
	if err1 != nil {
		err = err1
		return 
	}

	defer resp.Body.Close()

	//循环读取网页数据
	body, err2 := ioutil.ReadAll(resp.Body)
	if err2 != nil {
		err = err2
		return
	}
	result = string(body)

	return
}

func main() {

	var start, end int
	fmt.Print("请输入start的页数（>=1）")
	fmt.Scan(&start)
	fmt.Print("请输的end的页数（>=start）")
	fmt.Scan(&end)

	working(start, end)

	fmt.Print(strconv.Itoa(start)+" "+strconv.Itoa(end))

}